package example.UDPTest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpServer {
    public static void main(String[] args) {
        // 创建 DatagramSocket，监听指定端口
        try (DatagramSocket socket = new DatagramSocket(8888)) {
            System.out.println("UDP 服务器启动，监听端口 8888...");
            
            byte[] buffer = new byte[1024];
            
            while (true) {
                // 准备接收数据包
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                
                // 接收数据（阻塞方法）
                socket.receive(packet);
                
                // 解析数据
                String received = new String(packet.getData(), 0, packet.getLength());
                System.out.println("收到来自 " + packet.getAddress() + ":" + 
                                 packet.getPort() + " 的消息: " + received);
                
                // 准备响应数据
                String response = "服务器已收到: " + received;
                byte[] responseData = response.getBytes();
                
                // 发送响应
                DatagramPacket responsePacket = new DatagramPacket(
                    responseData, responseData.length, 
                    packet.getAddress(), packet.getPort());
                socket.send(responsePacket);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}